//Datatables jack
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
    if ( typeof sNewSource != 'undefined' && sNewSource != null )
    {
        oSettings.sAjaxSource = sNewSource;
    }
    this.oApi._fnProcessingDisplay( oSettings, true );
    var that = this;
    var iStart = oSettings._iDisplayStart;
     
    oSettings.fnServerData( oSettings.sAjaxSource, [], function(json) {
        /* Clear the old information from the table */
        that.oApi._fnClearTable( oSettings );
         
        /* Got the data - add it to the table */
        for ( var i=0 ; i<json.aaData.length ; i++ )
        {
            that.oApi._fnAddData( oSettings, json.aaData[i] );
        }
         
        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        that.fnDraw();
         
        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
        {
            oSettings._iDisplayStart = iStart;
            that.fnDraw( false );
        }
         
        that.oApi._fnProcessingDisplay( oSettings, false );
         
        /* Callback user function - for event handlers etc */
        if ( typeof fnCallback == 'function' && fnCallback != null )
        {
            fnCallback( oSettings );
        }
    }, oSettings );
}

var oTableReport;

$(document).ready(function() {
	$("#lista_reporte").hide();
	//Init select2 of doctors
	$.get('adminmain/getAllDoctorsRaw', function(data) {
			function patientFormatter(data) {
				return ""+data.lastname+', '+data.name+'';
			}
			oSelect = $("#id_doctor").select2({
				placeholder : "Buscar doctor...",
				minimumInputLength : 2,
				data : { 
					results: data, 
					text: function(item) { 
						return item.lastname+" "+item.name+" "+item.email+" "+item.dni; 
					} 
				},
				formatResult : patientFormatter, // omitted for brevity, see the source of this page
				formatSelection : patientFormatter, // omitted for brevity, see the source of this page
				dropdownCssClass : "bigdrop", // apply css that makes the dropdown taller
				escapeMarkup : function(m) {
					return m;
				} // we do not want to escape markup since we are displaying html in results
			})
			oSelect.on("change", function(e) { 
				openSchedule(e.val);
			})
		}, 'json');
	
	//Init select2 of patients
	$.get('secretarymain/xhrGetListOfPatients', function(data) {
			function patientFormatter(data) {
				return ""+data.lastname+', '+data.name+'';
			}
			oSelect = $("#id_patient").select2({
				placeholder : "Buscar paciente...",
				minimumInputLength : 2,
				data : { 
					results: data, 
					text: function(item) { 
						return item.lastname+" "+item.name+" "+item.email+" "+item.dni; 
					} 
				},
				formatResult : patientFormatter, // omitted for brevity, see the source of this page
				formatSelection : patientFormatter, // omitted for brevity, see the source of this page
				dropdownCssClass : "bigdrop", // apply css that makes the dropdown taller
				escapeMarkup : function(m) {
					return m;
				} // we do not want to escape markup since we are displaying html in results
			})
			oSelect.on("change", function(e) { 
				openSchedule(e.val);
			})
		}, 'json');
	
	//Init the socialhealth and specialities selects
	$("#erase_socialhealth").click( function(){
   		$("#id_socialhealth").prop("selectedIndex",0);
   		if( $(this).is(':checked') ) {
   			$("#id_socialhealth option[data-enable=0]").hide();
   			$("#id_socialhealth option[data-enable=1]").show();
   		} else {
   			$("#id_socialhealth option[data-enable=1]").show();
   			$("#id_socialhealth option[data-enable=0]").show();
   		}
	});
	
	$("#erase_speciality").click( function(){
		$("#id_speciality").prop("selectedIndex",0);
   		if( $(this).is(':checked') ) {
   			$("#id_speciality option[data-enable=0]").hide();
   			$("#id_speciality option[data-enable=1]").show();
   		} else {
   			$("#id_speciality option[data-enable=1]").show();
   			$("#id_speciality option[data-enable=0]").show();
   		}
	});
	
	$.get("http://localhost/clinica/adminmain/getAllSocialHealthRaw", function(data) {
		for (var index = 0; index < data.length; index++) {
			var option = "<option data-enable=\""+data[index].enable+"\" value=\""+data[index].id+"\">"+data[index].text+"</option>"
			$("#id_socialhealth").append(option);
		}
	},'json');
	
	$.get("http://localhost/clinica/adminmain/getAllSpecialitiesRaw", function(data) {
		for (var index = 0; index < data.length; index++) {
			var option = "<option data-enable=\""+data[index].enable+"\" value=\""+data[index].id+"\">"+data[index].text+"</option>"
			$("#id_speciality").append(option);
		}
	},'json');
	//init the forms submit
	$("#generate_btn").click(function() {
		$("#lista_reporte").show();
		if (!(typeof oTableReport === 'undefined')) {
			oTableReport.fnReloadAjax('http://localhost/clinica/bossmain/generateReport?'+$("#report_form").serialize());
			return false;
		} else {
			oTableReport = $("#lista_reporte").dataTable({
				"bProcessing": true,
				"sDom": 'T<"clear">lfrtip',
		        "oTableTools": {
		            "sSwfPath": "../../../../clinica/public/img/copy_csv_xls_pdf.swf"
		        },
	       	 	"sAjaxSource": 'http://localhost/clinica/bossmain/generateReport?'+$("#report_form").serialize(),
	       	 	"aoColumnDefs": [ 
	       	 		{
	        	      "aTargets": [ 0 ],
	        	      "mRender": function ( data, type, row ) {
	        	    	//This function takes care of render the actions column
	                  	var htmlAction = '';
	                  	if (data.docDniType == 0) {
	                  		dniType = "DNI";
	                  	}
	                  	if (data.docDniType == 1) {
	                  		dniType = "Pasaporte";
	                  	}
	                  	if (data.docDniType == 2) {
	                  		dniType = "LC";
	                  	}
	                  	dniType = 
	                  	htmlAction += data.docName+", "+data.docLastname+". "+data.docDni+" ("+dniType+")";
	                  	return htmlAction;
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 1 ],
	        	      "mRender": function ( data, type, row ) {
	        	    	//This function takes care of render the actions column
	                  	var htmlAction = '';
	                  	if (data.patDniType == 0) {
	                  		dniType = "DNI";
	                  	}
	                  	if (data.patDniType == 1) {
	                  		dniType = "Pasaporte";
	                  	}
	                  	if (data.patDniType == 2) {
	                  		dniType = "LC";
	                  	}
	                  	dniType = 
	                  	htmlAction += data.patName+", "+data.patLastname+". "+data.patDni+" ("+dniType+")";
	                  	return htmlAction;
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 4 ],
	        	      "mData": "day",
	        	      "mRender": function ( data, type, row ) {
	        	    		dias = ["Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado"];
	        	    		return dias[data];
	        	      	}
	        	    },
	        	    {
	        	      "aTargets": [ 5 ],
	        	      "mData": "status",
	        	      "mRender": function ( data, type, row ) {
	        	    		estados = ["Pendiente", "Vencido", "Concretado"];
	        	    		return estados[data];
	        	      	}
	        	    },
	        	],
	            "aoColumns": [
	              { "mDataProp": function(source, type, val) {
	              		return source;
	              	}
	              },
		      	  { "mDataProp": function(source, type, val) {
	              		return source;
	              	}
	              },
		      	  { "mDataProp": "speciality" },
	              { "mDataProp": "socialHealth" },
	              { "mDataProp": "day" },
	              { "mDataProp": "status" }
	            ],
	            "oLanguage": {
	            	"sProcessing":     "Procesando...",
	                "sLengthMenu":     "Mostrar _MENU_",
	                "sZeroRecords":    "No se encontraron resultados",
	                "sEmptyTable":     "Ningun dato disponible en esta tabla",
	                "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
	                "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
	                "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
	                "sInfoPostFix":    "",
	                "sSearch":         "Filtrar",
	                "sUrl":            "",
	                "sInfoThousands":  ",",
	                "sLoadingRecords": "Cargando...",
	                "oPaginate": {
	                    "sFirst":    "Primero",
	                    "sLast":     "Ultimo",
	                    "sNext":     "Siguiente",
	                    "sPrevious": "Anterior"
	                }
	            }
			});
		}
		return false;
	});
	
});

